package com.ggcc.support.common.controller;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * SuperController
 *
 * @author Caratacus
 */
public class SuperController {


    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;


    /**
     * 把request参数转为map
     *
     * @param request
     * @return
     */
    public Map<String, String> getParameterMap(HttpServletRequest request) throws UnsupportedEncodingException {
        // 参数Map
        Map<?, ?> properties = request.getParameterMap();
        // 返回值Map
        Map<String, String> returnMap = new HashMap<String, String>();
        Iterator<?> entries = properties.entrySet().iterator();
        Map.Entry<String, Object> entry;
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry<String, Object>) entries.next();
            String name = entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    if(values.length == 1) {
                        value = values[i] + ",";
                    }else{
                        value += values[i] + ",";
                    }
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

}
